package com.wuzheng.wisgo.sanitation.cloud.service.picture.impl;

import com.wuzheng.wisgo.sanitation.cloud.constant.ErrorConst;
import com.wuzheng.wisgo.sanitation.cloud.model.picture.PictureDTO;
import com.wuzheng.wisgo.sanitation.cloud.paraandgetutil.FastDFSUtils;
import com.wuzheng.wisgo.sanitation.cloud.repository.entity.person.User;
import com.wuzheng.wisgo.sanitation.cloud.repository.entity.picture.Picture;
import com.wuzheng.wisgo.sanitation.cloud.service.picture.PictureService;
import com.wuzheng.wisgo.sanitation.framework.base.service.impl.BaseServiceImpl;
import com.wuzheng.wisgo.sanitation.framework.core.constant.SysRespEnum;
import com.wuzheng.wisgo.sanitation.framework.core.util.ServiceAssert;
import com.wuzheng.wisgo.sanitation.framework.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author：hoipang
 * @date：Created in 2019-12-11
 * @description：图片信息服务实现类
 * @modified By：
 * @version: 1.0
 */
@Service
public class PictureServiceImpl extends BaseServiceImpl<Picture> implements PictureService {
    @Resource
    FastDFSUtils fileDfsUtil;
    @Value("http://"+"${fdfs.reqHost}")
    private String host;
    @Value("${fdfs.reqPort}")
    private String port;

    @Override
    public PictureDTO upload(User user, MultipartFile multipartFile) {
        String path = "";
        try {
            path = fileDfsUtil.upload(multipartFile);
            ServiceAssert.isTrue(StringUtils.isNotBlank(path), SysRespEnum.SERVICE_EXCEPTION.getCode(),
                    ErrorConst.Common.UPLOAD_FAILED);
        } catch (Exception e) {
            ServiceAssert.isTrue(false, SysRespEnum.SERVICE_EXCEPTION.getCode(), e.getMessage());
        }
        Picture picture = new Picture();
        picture.setCustomerId(user.getCustomerId());
        picture.setPictureName(path.substring(path.lastIndexOf("/") + 1));
        picture.setDomain(host.concat(":").concat(port).concat("/"));
        picture.setPictureUrl(path);
        picture.setDeFlag(false);
        picture.setCreator(user.getName());
        picture.setCreateTime(new Date());
        this.insert(picture);

        PictureDTO pictureDTO = new PictureDTO(picture.getId(), picture.getDomain().concat(picture.getPictureUrl()));
        return pictureDTO;
    }

    @Override
    public void deleteFile(String fileUrl) {
        fileDfsUtil.deleteFile(fileUrl);
    }
}
